package com.xyh.concurrency.example.Thread;

import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.TIMEOUT;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ExecutorsDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    log.info("结束");
                }
            });
        }
        executorService.shutdown();
    }

    public static void newFixedThreadPool() {
        /**
         * 制定线程数 线程池 创建方式
         */
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                log.info("结束");
            }
        });

    }

    public static void newSingleThreadExecutor() {
        /**
         *    创建只允许一个线程线程执行的线程池
         */

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                log.info("结束");
            }
        });
    }

    public static void newScheduledThreadPool() {
        /**
         * 创建线程延期多少秒进行执行
         */
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(100);
        /**
         * 创建延时时间
         */
        scheduledExecutorService.schedule(new Runnable() {
            @Override
            public void run() {
                log.info("结束");
            }
        }, 3, TimeUnit.SECONDS);

        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {

            }
        }, 1, 3, TimeUnit.SECONDS);
        /**
         * 建议使用  ScheduledExecutorService 来替换 timer
         * 定时timer
         */
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                log.info("结束");
            }
        }, new Date(), 5 * 1000);
    }
}
